package com.jay.media.music.core.provider

/**
 * Create by xuzhou4
 * Date 2021/11/8
 */
object MusicIDHelper {

    const val MEDIA_ROOT_ID = "__ROOT__"

    const val MEDIA_ID_MUSICS = "__ALL__"
    const val MEDIA_ID_MUSICS_BY_GENRE = "__BY_GENRE__"
    const val MEDIA_ID_MUSICS_BY_SEARCH = "__BY_SEARCH__"

    const val MEDIA_ID_MUSICS_BY_ARTIST = "__BY_ARTIST__"
    const val MEDIA_ID_MUSICS_BY_ALBUM = "__BY_ALBUM__"

    private const val CATEGORY_SEPARATOR = "//"
    private const val LEAF_SEPARATOR = '|'

    fun isBrowseable(mediaID: String): Boolean {
        return mediaID.indexOf(LEAF_SEPARATOR) < 0
    }

    fun createMediaID(musicID: String?, vararg categories: String?): String {
        val sb = StringBuilder()
        for (i in categories.indices) {
            require(isValidCategory(categories[i])) { "Invalid category: " + categories[i] }
            sb.append(categories[i])
            if (i < categories.size - 1) {
                sb.append(CATEGORY_SEPARATOR)
            }
        }
        if (musicID != null) {
            sb.append(LEAF_SEPARATOR).append(musicID)
        }
        return sb.toString()
    }

    private fun isValidCategory(category: String?): Boolean {
        return category == null ||
                category.indexOf(CATEGORY_SEPARATOR) < 0 &&
                category.indexOf(LEAF_SEPARATOR) < 0
    }

    fun getHierarchy(mediaId: String): Array<String?> {
        var mediaID = mediaId
        val pos = mediaID.indexOf(LEAF_SEPARATOR)
        if (pos >= 0) {
            mediaID = mediaID.substring(0, pos)
        }
        return mediaID.split(CATEGORY_SEPARATOR.toString()).toTypedArray()
    }

    fun extractMusicIDFromMediaID(mediaID: String): String? {
        val pos = mediaID.indexOf(LEAF_SEPARATOR)
        return if (pos >= 0) {
            mediaID.substring(pos + 1)
        } else mediaID
    }
}